package cn.kfu.service.impl;

import cn.kfu.mapper.AdministratorMapper;
import cn.kfu.pojo.Administrator;
import cn.kfu.service.AdminService;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;

@Service
@Transactional
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdministratorMapper administratorMapper;

    @Override
    public List<Administrator> findAll() {
        return administratorMapper.selectList(null);
    }

    @Override
    public void deleteById(Integer id) {
        administratorMapper.deleteById(id);
    }

    @Override
    public Administrator findUserByUsername(String username) {
        Wrapper<Administrator> wrapper = new EntityWrapper<>();
        wrapper.eq("username", username);
        List<Administrator> adminList = administratorMapper.selectList(wrapper);
        if (adminList != null && adminList.size() > 0) {
            return adminList.get(0);
        }
        return null;
    }

    @Override
    public Set<String> findRolesByUsername(String username) {
        return administratorMapper.findRolesByUsername(username);
    }

    @Override
    public Set<String> findPermissionsByUsername(String username) {
        return administratorMapper.findPermissionsByUsername(username);
    }

    public void saveAdmin(Administrator admin) {
        String password = admin.getPassword();
        String salt = RandomStringUtils.randomNumeric(6, 8);
        admin.setPrivateSalt(salt);
        Md5Hash md5Hash = new Md5Hash(password, salt); // 模拟md5加密一次
        admin.setPassword(md5Hash.toString());
        admin.setUserStatus("1");
        administratorMapper.insert(admin);
    }

}
